<template>
	<view class="container">
		<!-- 顶部积分区域 -->
		<view class="points-area">
			<view class="points-info">
				<text class="points-title">我的积分</text>
				<view class="points-actions">
					<view @click="toSpuDetails()">
						<button class="action-btn">积分明细</button>
					</view>
					<view @click="jiFenGuiZe()">
						<button class="action-btn">积分规则</button>
					</view>
				</view>
			</view>
			<view class="points-number">
				<text class="number">{{ user.integral }}</text>
			</view>
			<view class="points-description">
				<text class="description">今日签到 +{{ user.todayIntegral }}</text>
			</view>
			<image class="star-icon" src="https://aw2025ht.kangye.xyz/api/profile/upload/wdjfscxx.png" mode="aspectFit">
			</image>
		</view>

		<!-- 签到区域 -->
		<view class="check-in-area">
			<view class="check-in-title">
				<text class="check-in-text">已连续签到 <text style="color:#f47600"> {{ user.signDays }} </text> 天 </text>
				<button v-if="isQianDao == '签到'" class="check-in-btn" @click="handleSign">立即签到</button>
			</view>
			<view class="check-in-calendar">
				<scroll-view class="calendar-scroll" scroll-x="true">
					<view class="calendar-wrapper">
						<view v-for="(day, index) in visibleCalendar" :key="index" class="calendar-day">
							<view class="day-number" :class="{ 'signed': day.signed }">
								{{ day.day }}
							</view>
							<text class="day-month">{{ day.date }}</text>
						</view>
					</view>
				</scroll-view>
			</view>
		</view>
	</view>


	<!-- <image class="star-icon" src="/static/image/wdjfscxx.png" mode="aspectFit"></image> -->
	<!-- <image  src="https://aw2025ht.kangye.xyz/api/profile/upload/RTkJqu4KOxiy.png" mode="aspectFill"></image> -->
	<view class="container1">
		<view class="daoHang">
			<text class="jfdh">积分兑换</text>
			<view @click="toWoDeDingDan">
				<text class="wddd">

					我的订单 &gt;

				</text>
			</view>
		</view>

		<!-- 商品卡片区域 -->
		<view class="goods-container">
			<view class="goods-card" v-for="(item, i) in goodsList" :key="i" @click="goToGoodsDetail(item)">
				<image :src="item.image" mode="aspectFit"></image>
				<view class="goods-info">
					<view class="goods-title">{{ item.name }}</view>
					<!-- <view class="goods-desc">{{ item.desc }}</view> -->
					<!-- <view class="jiFenDuiHuanView"> -->
					<view class="goods-price">
						<text class="price-text">{{ item.jiFen }}</text>
						<text class="price-unit">积分</text>
						<!-- 判断用户积分是否足以兑换此商品，足够才显示去兑换，否则就是积分不足 -->
						<!-- {{user.integral >= item.jiFen}} -->
						<!-- {{user.integral }} -->
						<!-- {{ item.jiFen}} -->
						<view v-if="user.integral >= item.jiFen">
							<button class="exchange-btn">去兑换</button>
						</view>
						<view v-else>
							<button class="exchange-btn-buZu">积分不足</button>
						</view>

					</view>

					<!-- </view> -->
				</view>
			</view>
		</view>

		<!-- 底部提示 -->
		<view class="bottom-tip">没有更多了哦~</view>
	</view>

	<!-- 积分规则弹窗 -->
	<view v-if="showJiFenRules" class="jiFen-rules-modal">
		<view class="modal-content">
			<view class="modal-header">
				<text class="modal-title">积分规则</text>
				<text class="close-btn" @click="closeJiFenRules">×</text>
			</view>
			<view class="modal-body">
				<rich-text :nodes="jiFenRulesContent"></rich-text>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from 'vue';

	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app'


	import uniNavBar from '@dcloudio/uni-ui/lib/uni-nav-bar/uni-nav-bar.vue';
	import {
		useStore
	} from '@/store/counter.js'

	// 在onshow的时候，获取积分
	onShow(async () => {
		//发送请求，去后台，获取积分
		// 替换掉

		let login = uni.getStorageSync('login_data')
		let uid = login.uid;
		console.log(uid, 333);
		let res = await passenger.selectJiFenByUserId(uid);
		let jifen = res.data;
		console.log(jifen, 22)
		qianDaoJiFen.value = jifen;
		user.integral = jifen;
		uni.setStorageSync("qianDaoJiFen", qianDaoJiFen.value);
	})

	const useStoreObj = useStore();
	// 模拟商品数据
	const goodsList = ref([{
			id: 1,
			name: 'RTP胜肽抗皱紧致眼霜',
			desc: '紧致补水保湿眼霜',
			jiFen: 199,
			image: 'https://aw2025ht.kangye.xyz/api/profile/upload/sku1.png',
			stock: true,
		},
		{
			id: 2,
			name: '水润透亮水感弹润',
			desc: '烟酰胺补水保湿霜',
			jiFen: 399,
			image: '<url id="cvhl4vtm2cir15cnn6ng" type="url" status="failed" title="" wc="0">https://via.placeholder.com/150</url> ',
			stock: true,
		},
		{
			id: 3,
			name: '柔嫩保湿',
			desc: '滋润不黏腻',
			jiFen: 299,
			image: '<url id="cvhl4vtm2cir15cnn6ng" type="url" status="failed" title="" wc="0">https://via.placeholder.com/150</url> ',
			stock: true,
		},
		{
			id: 4,
			name: '益生菌',
			desc: '双重美肤',
			jiFen: 99,
			image: '<url id="cvhl4vtm2cir15cnn6ng" type="url" status="failed" title="" wc="0">https://via.placeholder.com/150</url> ',
			stock: true,
		},
		{
			id: 5,
			name: '保湿效果',
			desc: '洗卸一体',
			jiFen: 329,
			image: '<url id="cvhl4vtm2cir15cnn6ng" type="url" status="failed" title="" wc="0">https://via.placeholder.com/150</url> ',
			stock: true,
		},
		{
			id: 6,
			name: '立美丝凡士林保湿霜立美丝凡士林保湿霜立美丝凡士林保湿霜立美丝凡士林保湿霜立美丝凡士林保湿霜立美丝凡士林保湿霜',
			desc: '润肤霜身体乳',
			jiFen: 399,
			image: '<url id="cvhl4vtm2cir15cnn6ng" type="url" status="failed" title="" wc="0">https://via.placeholder.com/150</url> ',
			stock: false,
		},
	]);

	// 跳转到我的订单
	const toWoDeDingDan = () => {
		uni.navigateTo({
			url: '/packagenew/pages/dingDanXiangQing/dingDanXiangQing',
		});
	};

	// 跳转到商品详情
	const goToGoodsDetail = (item) => {
		if (user.integral < item.jiFen) {
			uni.showToast({
				title: '积分不足',
				icon: 'none',
			});
			return;
		}
		// 把item传过去1
		// useStoreObj.shangPinObj.value(item);
		useStoreObj.shangPinObj.value = item;
		uni.navigateTo({
			url: `/package/pages/skuDetails/skuDetails`,
		});


		// wx.navigateToMiniProgram({
		//   appId: 'wxe9094455e312c8ce', // 需要替换为微信小店的实际appId
		//   path: '#微信小店://奥维生物企业店/gh8l23GyVdkZVrd', // 需要替换为微信小店的实际页面路径
		//   extraData: {
		//     // 需要传递的额外数据
		//   },
		//   envVersion: 'release', // 可选值：develop（开发版）、trial（体验版）、release（正式版）
		//   success(res) {
		//     // 跳转成功后的回调
		//     console.log('跳转成功', res);
		//   },
		//   fail(err) {
		//     // 跳转失败后的回调
		//     console.error('跳转失败', err);
		//   }
		// });
	};

	// ------------------------------------------------------------------------------
	import {
		passenger
	} from '@/api/index.js';
	import {
		reactive
	} from 'vue';
	let zuoshou = uni.getStorageSync("isQianDao") == null || uni.getStorageSync("isQianDao") == '' ? "签到" : uni
		.getStorageSync("isQianDao");
	const isQianDao = ref(zuoshou);

	let zuoshou1 = uni.getStorageSync("qianDaoDay") == null || uni.getStorageSync("qianDaoDay") == '' ? "0" : uni
		.getStorageSync("qianDaoDay");
	const qianDaoDay = ref(zuoshou1);

	let zuoshou2 = uni.getStorageSync("qianDaoJiFen") == null || uni.getStorageSync("qianDaoJiFen") == '' ? "0" : uni
		.getStorageSync("qianDaoJiFen");
	const qianDaoJiFen = ref(zuoshou2);

	// 控制积分规则弹窗显示
	const showJiFenRules = ref(false);
	const jiFenRulesContent = ref('');

	// 积分规则按钮点击事件
	const jiFenGuiZe = async () => {
		try {
			// 调用后台接口获取积分规则数据
			const data = await passenger.getJiFenGuiZe(); // 假设有一个获取积分规则的接口
			if (data && data.data) {
				// jiFenRulesContent.value = data.data; // 假设返回的数据中有一个content字段包含规则内容
				// showJiFenRules.value = true;
				uni.showToast({
					title: data.data,
					icon: 'none',
					duration: 3000
				});
			} else {
				uni.showToast({
					title: '获取积分规则失败',
					icon: 'none'
				});
			}
		} catch (error) {
			console.error('获取积分规则失败:', error);
			uni.showToast({
				title: '获取积分规则失败',
				icon: 'none'
			});
		}
	};

	// 关闭积分规则弹窗
	const closeJiFenRules = () => {
		showJiFenRules.value = false;
	};

	const user = reactive({
		integral: Number(zuoshou2),
		todayIntegral: Number(zuoshou1),
		signDays: Number(zuoshou1)
	});

	const toSpuDetails = () => {
		//跳转商品详情页面
		uni.navigateTo({
			url: '/packagenew/pages/jiFenMingXi/jiFenMingXi'
		});
	};

	const visibleCalendar = ref([]);

	// 生成动态日历
	const generateVisibleCalendar = () => {
		const days = [];
		const baseDate = new Date();
		const ds = 7; // 固定显示7天

		// 计算起始天数
		const startDay = user.signDays <= ds ? 1 : user.signDays - (ds - 1);

		for (let i = 0; i < ds; i++) {
			let currentDay = startDay + i + 1;
			const dateOffset = user.signDays + i;
			const currentDate = new Date(baseDate);

			if (user.signDays < 7) {
				currentDay = startDay + i;

				if (isQianDao.value == "签到") {
					if (user.signDays > 0) {
						currentDate.setDate(currentDate.getDate() + i - user.signDays);
					} else {
						currentDate.setDate(currentDate.getDate() + i);
					}
				} else {
					currentDate.setDate(currentDate.getDate() + i - user.signDays + 1);
				}
			} else {
				currentDay = startDay + i + 2;
				let a = 0;
				a = 5 - i;

				if (isQianDao.value != "签到") {
					currentDay = startDay + i + 1;
					a = 5 - i;
				}
				currentDate.setDate(currentDate.getDate() - a);
			}

			days.push({
				day: currentDay,
				date: `${currentDate.getMonth() + 1}.${currentDate.getDate()}`,
				signed: currentDay <= user.signDays
			});
		}
		return days;
	};

	const handleSign = async () => {
		user.signDays++;
		isQianDao.value = "已签到";
		user.integral += user.todayIntegral;
		visibleCalendar.value = generateVisibleCalendar();

		// 登陆才可以签到
		let login_data = uni.getStorageSync("login_data");

		if (login_data.type != "login") {
			uni.showToast({
				title: "未登录不能签到",
				icon: "none",
				duration: 2000
			});
			return;
		}

		// 点击签到按钮
		let data = await passenger.qianDaos(qianDaoDay.value); // 把天数传过去。
		if (data != null && data.data != null && data.data == '签到成功') {
			isQianDao.value = "已签到";
			uni.setStorageSync("isQianDao", "已签到");
			qianDaoDay.value = Number(qianDaoDay.value) + 1;
			uni.setStorageSync("qianDaoDay", qianDaoDay.value);
			// 修改本地存储添加的积分数量
			qianDaoJiFen.value = Number(qianDaoJiFen.value) + Number(qianDaoDay.value);
			uni.setStorageSync("qianDaoJiFen", qianDaoJiFen.value);
			uni.showToast({
				title: '签到成功，获得' + user.todayIntegral + '积分',
				icon: 'success'
			});
			return;
		}
	};

	onMounted(async () => {
		qianDaoJiFen.value = uni.getStorageSync("qianDaoJiFen");
		isQianDao.value = uni.getStorageSync("isQianDao");
		qianDaoDay.value = uni.getStorageSync("qianDaoDay");

		visibleCalendar.value = generateVisibleCalendar();

		if (isQianDao.value == "签到") {
			user.todayIntegral = user.todayIntegral + 1;
		}

		// 挂载事件，去后台搜索商品列表goodsList
		let data = await passenger.selectAllJiFenShangPin();
		if (data != null && data.data != null) {
			goodsList.value = data.data;
		}
	});
</script>

<style scoped>
	.goods-card image {
		height: 150px;
		width: 100%;
	}

	.jiFenDuiHuanView {
		display: flex;
	}

	.daoHang {
		display: flex;
		justify-content: space-between;
		padding: 10px 10px 5px 10px;
	}

	.jfdh {
		color: #f26b1a;
		font-weight: 700;
		font-size: 16px;
	}

	.wddd {
		color: #333;
		font-size: 14px;
	}

	.container1 {
		padding: 0 20rpx;
	}

	.goods-container {
		margin-top: 20rpx;
		display: grid;
		grid-template-columns: repeat(auto-fill, minmax(320rpx, 1fr));
		gap: 20rpx;
		padding: 0 10rpx;
	}

	.goods-card {
		background-color: #fff;
		border-radius: 10rpx;
		overflow: hidden;
		box-shadow: 0 0 10rpx rgba(0, 0, 0, 0.1);
		display: flex;
		flex-direction: column;
	}

	.goods-image {
		width: 100%;
		height: auto;
		min-height: 200rpx;
	}

	.goods-info {
		padding: 20rpx;
		flex-grow: 1;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}

	.goods-title {
		font-size: 28rpx;
		font-weight: bold;
		margin-bottom: 10rpx;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.goods-desc {
		font-size: 24rpx;
		color: #666;
		margin-bottom: 10rpx;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.goods-price {
		display: flex;
		align-items: baseline;
		margin-bottom: 15rpx;
	}

	.price-text {
		font-size: 32rpx;
		color: #ff5722;
		font-weight: bold;
	}

	.price-unit {
		font-size: 24rpx;
		color: #ff5722;
		margin-left: 5rpx;
	}

	.exchange-btn-buZu {
		margin: 0 0 0 15px;
		/* width: 100%; */
		height: 50rpx;
		background-color: #f5f5f5;
		color: #999999;
		border: 1px solid #999999;
		border: none;
		border-radius: 30rpx;
		line-height: 50rpx;
		font-size: 24rpx;
	}

	.exchange-btn {
		margin: 0 0 0 15px;
		/* width: 100%; */
		height: 50rpx;
		background-color: #ff9800;
		color: #fff;
		border: none;
		border-radius: 30rpx;
		line-height: 50rpx;
		font-size: 24rpx;
	}

	.bottom-tip {
		text-align: center;
		padding: 20rpx 0;
		color: #999;
		font-size: 24rpx;
	}

	.container {
		background-color: #f5f5f5;
		padding: 0;
		overflow: hidden;
	}

	/* 积分区域样式 */
	.points-area {
		background: linear-gradient(to bottom, #f36d00, #ffdd67);
		border-radius: 0 0 50% 50% / 0 0 10% 10%;
		height: 401rpx;
		padding: 5rpx 40rpx;
		position: relative;
		overflow: hidden;
	}

	.points-info {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 30rpx;
	}

	.points-title {
		font-size: 36rpx;
		font-weight: bold;
		color: white;
	}

	.points-actions {
		display: flex;
	}

	.action-btn {
		/* margin-left: 20rpx; */
		color: white;
		font-size: 28rpx;
		padding:7px;


		 border: none;
		  background: none;
		  margin: 0;
		  cursor: pointer;
		  &::after {
		    border: none;
		  }
	}

	.points-number {
		margin-bottom: 20rpx;
	}

	.number {
		font-size: 80rpx;
		font-weight: bold;
		color: white;
	}

	.points-description {
		margin-bottom: 49rpx;
	}

	.description {
		font-size: 28rpx;
		color: rgba(255, 255, 255, 0.8);
	}

	.star-icon {
		position: relative;
		bottom: 244rpx;
		left: 35%;
		height: 402rpx;
	}

	/* 签到区域样式 */
	.check-in-area {
		background-color: white;
		border-radius: 20rpx;
		padding: 20rpx;
		margin: -97rpx 32rpx 0;
		box-shadow: 0 10rpx 20rpx rgba(0, 0, 0, 0.05);
		position: relative;
		z-index: 10;
	}

	.check-in-title {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
	}

	.check-in-text {
		font-size: 32rpx;
		font-weight: bold;
	}

	.check-in-btn {
		background-color: #ffdc64;
		color: #f26b00;
		border: none;
		border-radius: 50rpx;
		font-size: 28rpx;
		margin: 0;
		font-weight: bold;
		height: 30px;
		line-height: 30px;
	}

	.check-in-calendar {
		position: relative;
		height: 120rpx;
	}

	.calendar-scroll {
		width: 100%;
		height: 100%;
		white-space: nowrap;
	}

	.calendar-wrapper {
		display: inline-flex;
		width: 100%;
	}

	.calendar-day {
		display: flex;
		flex-direction: column;
		align-items: center;
		width: 34%;
		/* margin: 1px 9px; */
	}

	.day-number {
		width: 60rpx;
		height: 60rpx;
		border-radius: 50%;
		background-color: #f0f0f0;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 28rpx;
		margin-bottom: 10rpx;
	}

	.signed {
		background-color: #ff9800;
		color: white;
		font-weight: bold;
	}

	.day-month {
		font-size: 24rpx;
		color: #666;
	}

	/* 积分规则弹窗样式 */
	.jiFen-rules-modal {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 999;
	}

	.modal-content {
		background-color: white;
		width: 80%;
		border-radius: 10rpx;
		overflow: hidden;
	}

	.modal-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx;
		border-bottom: 1px solid #f0f0f0;
	}

	.modal-title {
		font-size: 32rpx;
		font-weight: bold;
	}

	.close-btn {
		font-size: 40rpx;
		color: #999;
	}

	.modal-body {
		padding: 20rpx;
		min-height: 300rpx;
	}
</style>